<template>
	<view class="withdraw">
		<view class="head">
			<view>取件</view>
			<view class="circle-btn">
				<text class="txt" @click="back">返</text>
			</view>
		</view>

		<view class="info-area">

			<view class="save-warehouse">

				<view class="input-area input-area-fix">
					<view class="circle-btn">
						<text class="txt">取</text>
					</view>
					<!-- 	<input placeholder="从哪个仓库取出" class="my-input"
							placeholder-style="color: rgba(255,255,255, 1);" /> -->
					<picker mode="selector" :range="showWarehouseNames" :value="selectedWarehouseIndex" @change="onWarehouseChange" class="my-big-picker">

                        <text v-if="selectedWarehouseIndex === -1" style="color: rgba(255, 255, 255, 0.4)">从哪个仓库取出</text>
						<text  v-else> {{wareHouseList[selectedWarehouseIndex].wareHouseName}} </text>
					</picker>
				</view>

				<!-- 龙殿派送 -->
				<view v-if="this.way == 1">
					<view class="input-area input-area-fix">
						<view class="circle-btn circle-btn-black">
							<text class="txt">收</text>
						</view>
						<input v-model="homeDeliveryAddress" placeholder="要哪里收件" class="my-big-picker" placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>

				</view>

			</view>
		</view>

		<view class="ways">
			<view class="fade-white-font-color">寄件方式</view>
			<view class="way" :class="[ this.way == 0  ? 'active' : '']"
				@click="()=> this.way = 0"> 服务点自取 </view>
			<view class="way" :class="[ this.way == 1 ? 'active' : '']" @click="()=> this.way = 1">
				龙殿派送</view>
		</view>

		<view class="info-form">
			<form @submit="formSubmit">
				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">物品信息</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<!-- <input v-model="formData.goodId" placeholder="请输入物品信息"
							placeholder-style="color: rgba(255,255,255, 0.8);" /> -->
						<picker :range="goodList.map(item => item.goodName)" :value="selectedIndex" @change="onPickerChange">
						          <view class="picker">
						            <text v-if="selectedIndex === -1 || !goodList[selectedIndex]" style="color: rgba(255, 255, 255, 0.4)">请选择物品信息 > </text>
						            <text v-else>{{goodList[selectedIndex].goodName }}</text>
						          </view>
					    </picker>
					</view>
				</view>


				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">联系人</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.contactPerson" placeholder="请输入联系人"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>
				</view>

				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">手机号</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.contactPhone" placeholder="请输入手机号"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>
				</view>

				<view class="form-item" v-if="this.way == 1">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">上门时间</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area" @click="open">
						<!-- <input v-model="formData.doorTime"  placeholder="xxxx" placeholder-style="color: rgba(255,255,255, 0.8);" /> -->

						<!-- <picker mode="date" :value="formData.appointmentTime" :start="getTodayDate()" end="2035-12-31"
							@change="onDateChange($event, 'appointmentTime')">
							<view class="picker">
								<text v-if="!formData.appointmentTime" style="color: rgba(255,255,255, 0.4)">请选择 ></text>
								<text v-else>{{ formData.appointmentTime }}</text>
							</view>
						</picker> -->
						
						<text v-if="!formData.appointmentTime" style="color: rgba(255, 255, 255, 0.4)">请选择上门时间 ></text>
						<text style="color: white;" v-else>{{ formData.appointmentTime }}</text>
						
					</view>
				</view>


				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">备注</view>
							<!-- <view class="requiedFlag">
							  必填
						  </view> -->
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.remark" placeholder="请输入备注"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>
				</view>
			</form>
			
			<liuDeliveryTime  @change="appointmentTimeChange" ref="chooseTime" title="请选择上门时间">
			</liuDeliveryTime>
		</view>


		<view class="order">
			<!-- <view class="orderHelp">
				<view class="title">填写收寄地址后看预估费用</view>
				<view class="tip fade-white-font-color">按照一公斤内物品+距离+存储时间估计 </view>
			</view> -->

			<view class="order-btn linear-gradient-order" @click="formSubmit">
				立即下单
			</view>
		</view>
	</view>
</template>

<script>
	import * as api from '../../utils/api.js'
	import { checkPhone } from '../../utils/untils.js';
	import liuDeliveryTime from '../../components/liu-delivery-time.vue';
	export default {
		components: {
			liuDeliveryTime
		},
		data() {
			return {
				wareHouse: '',
				wareHouseList: [],
				homeDeliveryAddress: null,
				selectedWarehouseIndex: -1,
				eltrInfoOptions: [{
						label: '苹果',
						value: 'apple'
					},
					{
						label: '香蕉',
						value: 'banana'
					},
					{
						label: '橙子',
						value: 'orange'
					}
				],
				options: ['苹果', '香蕉', '橙子', '葡萄'],
				way: 0, // 0 服务店自寄 1 上门取件
				selectedIndex: -1,
				goodList: [], // 当前仓库下的商品列表
				formData: {
					goodId: '',
					contactPerson: null,
					contactPhone: null,
					appointmentTime: '',
				}
			}
		},
		computed: {
			showWarehouseNames () {
				if (!this.wareHouseList || !this.wareHouseList.length) return []
				return this.wareHouseList.map(item => item.wareHouseName);
			},
		},
		onLoad() {
		  this.getWareHouseList();
		},
		methods: {
			open() {
				this.$refs.chooseTime.open()
			},
			appointmentTimeChange(e) {
				this.formData.appointmentTime = e.value;
			},
			async getWareHouseList () {
				const res = await api.wareHouseList();
				this.wareHouseList = (res.rows || []).filter(v=> v)
			},
			async getPersonalGoodsList () {
				const  selectedWarehouse = this.wareHouseList[this.selectedWarehouseIndex];
				if (this.selectedWarehouseIndex == -1 || !selectedWarehouse) return;
				const wareHouseId = selectedWarehouse.wareHouseId;
				const res = await api.personalGoodsList({wareHouseId, pageNum: 1, pageSize: 10000 });
				this.goodList = (res.rows || []).filter(v=> v)
			},
			
			
			onWarehouseChange(e) {
				const index = e.detail.value;
				this.selectedWarehouseIndex = e.detail.value;
				this.getPersonalGoodsList();
			},
			onPickerChange(e) {
				// 更新选中的索引
				this.selectedIndex = e.detail.value;
				// 根据索引获取实际选中的值
				this.formData.goodId = (this.goodList[this.selectedIndex])?.goodId;
				console.log('你选择的实际值是：', this.formData.goodId);
			},
			// 获取指定偏移天数后的日期的方法
			getTodayDate(offset = 0) {
				const date = new Date();
				// 根据偏移量调整日期
				date.setDate(date.getDate() + offset);
				const year = date.getFullYear();
				// 月份从 0 开始计数，所以要加 1
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			onDateChange(e, prop) {
				this.formData[prop] = e.detail.value;
				console.log('你选择的日期是：', this.formData[prop]);
			},
			back() {
				uni.navigateBack()
			},
			checkForm() {
				let errMsg = ''
				if (!this.formData.goodId) {
					errMsg = '物品信息必填'
				}

				if (!this.formData.contactPerson) {
					errMsg = '联系人必填必填'
				}
				if (!this.formData.contactPhone || checkPhone(this.formData.contactPhone)) {
					errMsg = '手机号格式不正确'
				}
				if (this.way == 1 && !this.formData.appointmentTime) {
					errMsg = '上门时间必填'
				}

				if (errMsg) {
					uni.showToast({
						title: errMsg,
						icon: 'none',
						duration: 2000
					});
				}

				return !errMsg;

			},
			// 提交成功后，跳转到下单成功页面
			async formSubmit(e) {
				const token = uni.getStorageSync('token');
				if (!token) {
					uni.redirectTo({
						url: '/pages/login/index'
					});
					return;
				}
                const selectedWarehouse = this.wareHouseList[this.selectedWarehouseIndex];
				if (!selectedWarehouse || !selectedWarehouse.wareHouseId) {
				  this.myToast('您还没有选择从哪个仓库取出')
				  return
				}
				const pass = this.checkForm();
				if (!pass) return
				const formData = this.formData;
                const  params = {
                	  wareHouseId: selectedWarehouse.wareHouseId,
                	  takeMethod: this.way == 1 ? 1 : 2,
                	  ...formData
                  };
				  
				  if (this.way == 0) { }  // 服务店自取
				  if (this.way == 1) { // 龙殿派送
				  	if (!this.homeDeliveryAddress) {
				  		return this.myToast('您还没有选择要哪里收件')	
				  	}
				  	params.pickUpAddress = this.homeDeliveryAddress;
				  }
 
				 const res = await api.insertTakeOrder(params);
				 
				 this.successCb(res, params.wareHouseId)	
		
			},

			successCb(res, wareHouseId) {
				this.myToast(res.msg);
				if (!res.code == 200) return

				const scene = this.way ? 'delivery' : 'self-take';
				const url = `/pages/orderFeedback/index?scene=${scene}&wareHouseId=${wareHouseId}`;
				uni.navigateTo({
					url: url,
					success() {
						console.log('跳转成功');
					},
					fail(err) {
						console.error('跳转失败', err);
					}
				});
			},

			myToast(msg, icon = 'none') {
				uni.showToast({
					icon: icon,
					title: msg,
					duration: 2000
				})
			},



		}
	}
</script>

<style lang="scss">
	.withdraw {
		color: white;
		padding: 40rpx 20rpx;
		align-items: center;



		.circle-btn {
			width: 90rpx;
			height: 90rpx;
			border-radius: 50%;
			text-align: center;
			line-height: 90rpx;
            background-color: #e7b34d;
			.txt {
				color: black;
				font-size: 22px;
			}
		}
	  .circle-btn-black {
		  background-color: rgba(0, 0, 0, 0.8);
		  .txt {
		  	  color: white;
		  }
	  }

		.sqaure-btn {
			width: 90rpx;
			height: 90rpx;
			border-radius: 8rpx;

			background-color: yellow;
			text-align: center;
			line-height: 90rpx;
			font-size: 40rpx;
			background-color: rgba(0, 0, 0, 1);

			.txt {
				color: white;
			}
		}

		// .linear-gradient-back {
		// 	background: linear-gradient(to bottom right, #f2ebce, #856925);
		// }

		// .linear-gradient-order {
		// 	background: linear-gradient(to bottom right, #ede5c1, #f8ce3d);
		// }

		.head {
			display: flex;
			padding: 40rpx 10rpx;
			justify-content: space-between;
			font-size: 46rpx;
			// background-color: rgba(0, 0, 0, 0.3);

		}

		.info-area {
			padding: 40rpx 10rpx;
			border-radius: 10rpx;

			.save-warehouse {
				.my-big-picker {
					font-size: 42rpx;
					color: white;
				}

				.input-area {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin: 20rpx 0 20rpx 0;
					padding: 16rpx 20rpx;
					border-radius: 10rpx;
					background-color: #333333;

					.my-input {
						font-size: 42rpx;
					}
				}

				.input-area-fix {
					gap: 40rpx;
					justify-content: start;
				}
			}
		}

		.ways {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 40rpx;
			margin: 60rpx 0;
			padding: 40rpx 10rpx;
			border-radius: 10rpx;
			background-color: rgba(0, 0, 0, 0.3);

			.way {
				color: white;
				border-radius: 8px;
				padding: 6px 30rpx;
				background-color: #2f2f2f;
			}

			.active {
				background-color: #e7b34d;
				color: black;
				// box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.5);  
			}
		}


		.info-form {
			font-size: 30rpx;
			padding: 40rpx 20rpx;
			border-radius: 10rpx;
			background-color: #333333;

			.form-item {
				display: flex;
				align-items: center;
				margin: 20rpx 0;

				.label-area {
					.txt {
						width: 5em;
						display: inline-block;
					}

					.requiedFlag {
						padding: 0 30rpx;
						display: inline-block;
						border-radius: 30rpx;
						background-color: #ff2b1d;
						color: white;
					}
				}

				.input-area {
					flex: 1;
					margin-left: 1em;
				}
			}
		}


		.order {
			position: fixed;
			bottom: 30rpx;
			right: 30rpx;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			margin-top: 50rpx;
			padding: 20rpx 22rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			border-radius: 10rpx;
			background-color: rgba(0, 0, 0, 0.3);

			//  .orderHelp {
			// .title {
			// 	font-size: 34rpx;
			// }
			// .tip {
			// 	font-size: 24rpx;
			// }  
			//  }
			.order-btn {
				padding: 5rpx 40rpx;
				display: inline-block;
				border-radius: 30rpx;
				background-color: #e7b34d;
				color: black;
				font-weight: bold;
				font-size: 40rpx;
			}
		}
	}
</style>